import json
from datetime import datetime
from typing import Dict, Any, Optional
from .utils.file_handler import FileHandler
from .utils.logger import Logger
from config.settings import GameSettings

class Statistics:
    def __init__(self):
        self.file_handler = FileHandler()
        self.logger = Logger('statistics')
        self.current_stats = self._load_stats()
    
    def _load_stats(self) -> Dict[str, Any]:
        """加载统计数据"""
        stats = self.file_handler.load_json(GameSettings.STATS_FILE)
        return stats if stats else self._init_stats()
    
    def _init_stats(self) -> Dict[str, Any]:
        """初始化统计数据"""
        return {
            'levels': {},
            'total_practice_time': 0,
            'last_practice': None,
            'history': []
        }
    
    def update_stats(self, level: str, correct: bool, time_spent: float):
        """更新统计数据"""
        if level not in self.current_stats['levels']:
            self.current_stats['levels'][level] = {
                'correct': 0,
                'wrong': 0,
                'total_time': 0,
                'best_wpm': 0
            }
        
        level_stats = self.current_stats['levels'][level]
        if correct:
            level_stats['correct'] += 1
        else:
            level_stats['wrong'] += 1
        
        level_stats['total_time'] += time_spent
        self.current_stats['total_practice_time'] += time_spent
        self.current_stats['last_practice'] = datetime.now().isoformat()
        
        # 计算当前WPM
        current_wpm = level_stats['correct'] / (level_stats['total_time'] / 60)
        level_stats['best_wpm'] = max(level_stats['best_wpm'], current_wpm)
        
        # 添加到历史记录
        self._add_to_history(level, correct, time_spent)
    
    def _add_to_history(self, level: str, correct: bool, time_spent: float):
        """添加历史记录"""
        history_entry = {
            'timestamp': datetime.now().isoformat(),
            'level': level,
            'correct': correct,
            'time_spent': time_spent
        }
        
        self.current_stats['history'].append(history_entry)
        
        # 限制历史记录数量
        if len(self.current_stats['history']) > GameSettings.MAX_HISTORY_RECORDS:
            self.current_stats['history'] = self.current_stats['history'][-GameSettings.MAX_HISTORY_RECORDS:]
    
    def get_level_stats(self, level: str) -> Optional[Dict[str, Any]]:
        """获取指定难度级别的统计数据"""
        return self.current_stats['levels'].get(level)
    
    def save_stats(self):
        """保存统计数据"""
        try:
            self.file_handler.save_json(GameSettings.STATS_FILE, self.current_stats)
            self.logger.info("Statistics saved successfully")
        except Exception as e:
            self.logger.error(f"Failed to save statistics: {str(e)}")
    
    def show_stats(self):
        """显示统计信息"""
        print("\n=== 统计信息 ===")
        print(f"总练习时间：{self.current_stats['total_practice_time']:.1f}秒")
        print(f"上次练习：{self.current_stats['last_practice']}")
        
        print("\n各难度级别统计：")
        for level, stats in self.current_stats['levels'].items():
            total = stats['correct'] + stats['wrong']
            if total > 0:
                accuracy = (stats['correct'] / total) * 100
                wpm = stats['correct'] / (stats['total_time'] / 60) if stats['total_time'] > 0 else 0
                print(f"\n{level} 难度：")
                print(f"正确次数: {stats['correct']}")
                print(f"错误次数: {stats['wrong']}")
                print(f"准确率: {accuracy:.1f}%")
                print(f"平均速度: {wpm:.1f} WPM")
                print(f"最佳速度: {stats['best_wpm']:.1f} WPM")
